from fastapi import APIRouter, Request, Depends, Form, HTTPException
from fastapi.responses import RedirectResponse, HTMLResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from auth.db import SessionLocal
from devices.models import Device  # 导入设备模型和心电记录模型
from ecg.models import ECGRecord
from auth.models import Alert  # 导入报警记录模型
from auth.utils import get_current_user_info

router = APIRouter()
templates = Jinja2Templates(directory="templates")


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 从 cookie 中提取当前用户名
def get_current_user(request: Request):
    username, role = get_current_user_info(request)  # 保证返回两个值
    if not username:
        raise HTTPException(status_code=401, detail="Not authenticated")
    return username, role

# 显示设备管理页面
@router.get("/devices", response_class=HTMLResponse)
def device_page(request: Request, db: Session = Depends(get_db)):
    username, role = get_current_user(request)
    if not username:
        return RedirectResponse(url="/login", status_code=303)

    devices = db.query(Device).filter(Device.owner == username).all()
    return templates.TemplateResponse("dashboard.html", {
        "request": request,
        "username": username,
        "devices": devices,
        "active_tab": "devices"
    })
# 添加设备
@router.post("/devices/add")
def add_device(
    request: Request,
    device_id: str = Form(...),
    name: str = Form(...),
    db: Session = Depends(get_db)
):
    username, role = get_current_user(request)
    if not username:
        return RedirectResponse(url="/login", status_code=303)

    import re

    # 校验设备编号格式：ECG + 4位年份 + 6位编号
    pattern = r"^ECG\d{4}\d{6}$"
    if not re.match(pattern, device_id):
        return RedirectResponse(url="/devices?msg=invalid_format", status_code=303)

    # 校验长度（保险）
    if len(device_id) != 13:
        return RedirectResponse(url="/devices?msg=invalid_length", status_code=303)

    # 校验设备名称长度
    if len(name) > 10:
        return RedirectResponse(url="/devices?msg=name_too_long", status_code=303)
    if not len(name):
        return RedirectResponse(url="/devices?msg=name_null", status_code=303)

    # 检查设备编号是否存在
    if db.query(Device).filter(Device.device_id == device_id).first():
        return RedirectResponse(url="/devices?msg=device_exists", status_code=303)

    # 检查设备名称是否存在
    if db.query(Device).filter(Device.name == name).first():
        return RedirectResponse(url="/devices?msg=device_name_exists", status_code=303)

    # 绑定成功
    device = Device(device_id=device_id, name=name, owner=username)
    db.add(device)
    db.commit()

    return RedirectResponse(url="/devices?msg=add_success", status_code=303)

# 删除设备
@router.get("/devices/delete/{device_id}")
def delete_device(device_id: str, request: Request, db: Session = Depends(get_db)):
    username, role = get_current_user(request)
    # 获取设备
    device = db.query(Device).filter(Device.device_id == device_id).first()
    if not device:
        return RedirectResponse(url="/devices?msg=device_not_found", status_code=303)
    # 如果当前用户是管理员或超级管理员，允许删除设备
    if role in ["admin", "superadmin"]:
        # 删除设备前，先删除相关的报警记录
        alerts = db.query(Alert).filter(Alert.device_id == device_id).all()
        for alert in alerts:
            db.delete(alert)
        # 假设你有 ECGRecord 模型与设备关联，删除相关的心电图数据
        ecg_records = db.query(ECGRecord).filter(ECGRecord.device_id == device_id).all()
        for ecg in ecg_records:
            db.delete(ecg)
        # 删除设备
        db.delete(device)
        db.commit()
        return RedirectResponse(url="/devices?msg=delete_success", status_code=303)
    # 如果是普通用户，只能删除自己拥有的设备
    if device.owner != username:
        return RedirectResponse(url="/devices?msg=permission_denied", status_code=303)
    # 删除设备前，先删除相关的报警记录
    alerts = db.query(Alert).filter(Alert.device_id == device_id).all()
    for alert in alerts:
        db.delete(alert)
    # 假设删除与设备关联的心电数据
    ecg_records = db.query(ECGRecord).filter(ECGRecord.device_id == device_id).all()
    for ecg in ecg_records:
        db.delete(ecg)
    # 删除设备
    db.delete(device)
    db.commit()
    return RedirectResponse(url="/devices?msg=delete_success", status_code=303)
